#include <stdio.h>
#include <string.h>
typedef struct
{
	char str[51];
	int num;
}DNA;
int comp(const void* a, const void* b)
{
	DNA* x = (DNA*)a;
	DNA* y = (DNA*)b;
	return x->num - y->num;
}
int main()
{
	int n,m,i=0,j,C,G,T,times;
	scanf("%d %d", &n, &m);
	DNA dna[m];
	while (i<m)
	{
		scanf("%s", dna[i].str);
		j=times=C=G=T=0;
		while(j<n)
		{
			if (dna[i].str[j] == 'A')
			{
				times += C + G + T;
			}
			if (dna[i].str[j] == 'C')
			{
				C++;
				times += G + T;
			}
			if (dna[i].str[j] == 'G')
			{
				G++;
				times += T;
			}
			if (dna[i].str[j] == 'T')
			{
				T++;
			}
			j++;
		}
		dna[i].num = times;
		i++;
	}
	qsort(dna, m, sizeof(DNA), comp);
	i=0;
	while (i<m)
	{
		printf("%s\n", dna[i].str);
		i++;
	}
	return 0;
}
